<template>
    <el-container class="container">
        <el-main class="main-container">
            <div class="chat-container" ref="chatContainer">
                <!-- 遍历消息列表 -->
                <div v-for="(msg, index) in messageList" :key="index"
                     :class="['message-item', msg.type === 'user' ? 'user-message' : 'ai-message']">
                    <el-text tag="b" v-if="msg.type === 'user'">{{ msg.content }} 👤</el-text>
                    <el-text tag="b" v-else>🤖 {{ msg.content }}</el-text>
                </div>
                <!-- 加载动画 -->
                <div v-if="loading" class="message-item ai-message">
                    <el-table v-loading="loading"
                              style="width: 100%;height: 100px"
                              element-loading-text="处理中..."
                              :element-loading-svg="svg"
                              class="custom-loading-svg"
                              element-loading-svg-view-box="-10, -10, 50, 50">
                    </el-table>
                </div>
            </div>
        </el-main>
        <el-footer class="footer-container">
          <div class="input-container">
            <el-input v-model="inputValue" style="width: 500px" placeholder="Please input" @keyup.enter="answer" />
            <el-button type="primary" style="margin-left: 10px" @click="answer()">回答</el-button>
            <el-button style="margin-left: 10px" @click="resetConversation()">新会话</el-button>
          </div>
        </el-footer>
    </el-container>
</template>

<script setup>


import {ref, watch, nextTick} from "vue";
import myAxios from "../../../plugins/myAxios.js";
import {ElMessage} from "element-plus";

const inputValue = ref('');
// const resValue = ref('大帅哥，你好啊~');
const messageList = ref([
    { type: 'ai', content: '你好，请输入你的问题~' }
]); // 新增消息列表

const loading = ref(false)
const svg = `
        <path class="path" d="
          M 30 15
          L 28 17
          M 25.61 25.61
          A 15 15, 0, 0, 1, 15 30
          A 15 15, 0, 1, 1, 27.99 7.5
          L 15 15
        " style="stroke-width: 4px; fill: rgba(0, 0, 0, 0)"/>
      `

// 添加防抖标志
let isDebouncing = false;

// 添加一个引用来获取聊天容器元素
const chatContainer = ref(null);

// 在 script setup 中添加 conversationId 的引用
const conversationId = ref('');

// 监听消息列表变化
watch(messageList, () => {
  // 使用 nextTick 确保 DOM 更新后再滚动
  nextTick(() => {
    if (chatContainer.value) {
      chatContainer.value.scrollTop = chatContainer.value.scrollHeight;
    }
  });
}, { deep: true });

// 防抖包装的 answer 方法
const answer = async () => {
    // 如果正在防抖中，直接返回
    if (isDebouncing) {
        ElMessage({
            type: 'warning',
            message: '请求太频繁，请稍后再试',
        })
        return;
    }

    if(inputValue.value.trim() === ''){
        return ElMessage({
            type: 'warning',
            message: '请输入答疑内容',
        })
    }

    try {
        // 设置防抖标志
        isDebouncing = true;

        // 添加用户消息
        messageList.value.push({
            type: 'user',
            content: inputValue.value
        });

        loading.value = true;
        const res = await myAxios.post('/answer/get/simple',{
            answerStr:inputValue.value,
            conversationId: conversationId.value // 添加会话ID参数
        },{timeout:30000})

        if(res.code === 0){
            // 如果是新会话，保存返回的会话ID
            if (res.data.conversationId) {
                conversationId.value = res.data.conversationId;
            }

            messageList.value.push({
                type: 'ai',
                content: res.data.content
            });
        }else{
            ElMessage.error(res.message);
        }
    } finally {
        loading.value = false;
        inputValue.value = '';

        // 设置防抖延时，2秒内不能再次触发
        setTimeout(() => {
            isDebouncing = false;
        }, 2000);
    }
}

// 添加重置会话的方法（可选）
const resetConversation = () => {
    conversationId.value = '';
    messageList.value = [
        { type: 'ai', content: '你好，请输入你的问题~' }
    ];
}

</script>

<style scoped lang="less">
.container{
  overflow: hidden;
  border-radius: 4px;
  //box-shadow: #8c939d;
}
.main-container{
  height: 700px;
  .chat-container {
        width: 100%;
        height: 100%;
        background: #F4F6F8;
        border-radius: 10px;
        // padding: 20px;
        // overflow-y: auto;
        overflow-x: hidden;   /* 隐藏水平滚动条 */

        // 隐藏滚动条但保持可滚动功能
        &::-webkit-scrollbar {
            display: none;
        }
        -ms-overflow-style: none;
        scrollbar-width: none;

        .message-item {
            margin-top: 20px;
            margin-bottom: 20px;
            display: inline-block;
            min-width: 100px;
            max-width: 70%;
            padding: 10px 15px;
            border-radius: 8px;
            word-wrap: break-word;

            &.user-message {
                margin-left: auto;
                background-color: #95EC69;
                float: right;
                clear: both;
                margin-right: 20px;
            }

            &.ai-message {
                margin-left: 20px;
                margin-right: auto;
                background-color: #ffffff;
                float: left;
                clear: both;
            }
        }
    }
}
.footer-container{
  height: 100px;
  //background: #a8acaf;
  .input-container{
    width: 100%;
    height: 100%;
    margin-left: 350px;
    margin-top: 18px;
  }
}

.loading-overlay {
  width: 100%;
  background-color: rgba(187, 70, 70, 0.8);
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>
